package com.example.springboot.service.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.entity.Logs;
import com.example.springboot.entity.User;
import com.example.springboot.service.LogsService;
import com.example.springboot.utils.IpUtils;
import com.example.springboot.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能:
 * 作者: sdj
 * 日期: 2025/1/16 22:22
 */
@Component
@Aspect
@Slf4j
public class LogsAspect {
    @Autowired
    private LogsService logsService;
    //后置通知
    @AfterReturning(pointcut = "@annotation(honeyLogs)",returning = "jsonResult")
    public void recordLog(JoinPoint joinPoint, HoneyLogs honeyLogs,Object jsonResult){
        //获取当前登录的用户的信息
        User logUser = TokenUtils.getCurrentUser();
        if (logUser == null){  //用户未登录的情况下,loginUser是null,是null的话，就从参数里面获取操作人信息
            //登陆、注册
            Object[] args= joinPoint.getArgs();//获取方法中的请求参数
            if (ArrayUtil.isNotEmpty(args)){
                if (args[0] instanceof User){
                    logUser = (User)args[0];
                }
            }

        }
        if (logUser==null){
            log.error("记录日志信息报错，未获取到当前用户信息");
            return;
        }

        //获取HttpServletRequest
        ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //获取IP
        String ipAddr = IpUtils.getIpAddr(request);

        //构建Logs对象
        Logs logs = Logs.builder()
                .user(logUser.getUsername())
                .operation(honeyLogs.operation())
                .type(honeyLogs.type().getValue())
                .ip(ipAddr)
                .time(DateUtil.now())
                .build();

        //hutool工具类生成异步类多线程
        //使用异步的方式，将数据插入到数据库中
        ThreadUtil.execAsync(()->{
            logsService.save(logs);
        });
    }
}
